package com.hzqy.web.filter;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hzqy.web.login.SessionKey;

import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 通过session监听器统计在线用户数
 * 
 * @author admin
 *
 */
public class MySessionListener implements HttpSessionListener,ServletRequestListener {
	private static final Log LOG = LogFactory.getLog(MySessionListener.class);
	HttpServletRequest request = null;

	/**
	 * session创建时调用 并将在线人数进行加一存入application
	 */
	public void sessionCreated(HttpSessionEvent event) {
		HttpSession session = event.getSession();
		ServletContext application = session.getServletContext();
		// 在application范围由一个ConcurrentHashMap集保存所有的session
		ConcurrentHashMap<String, HttpSession> userHash = null;
		Object obj = application.getAttribute(SessionKey.APPLICATION_ONLINE_USER);
		session.setAttribute(SessionKey.SESSION_CLIENT_IP, request.getRemoteAddr());
		if (obj == null) {// 第一位用户登入时创建对象存入application
			userHash = new ConcurrentHashMap<String, HttpSession>();
			userHash.put(session.getId(), session);
			application.setAttribute(SessionKey.APPLICATION_ONLINE_USER, userHash);
		} else {// 每次新用户登入对onlineCount加一
			userHash = (ConcurrentHashMap<String, HttpSession>) obj;
			userHash.put(session.getId(), session);
		}
		//LOG.debug(session.getId() + "有新用户访问业务，平台在线用户数为：" + userHash.size());
	}

	/**
	 * session消亡时调用 并将在线人数减一存入application
	 */
	public void sessionDestroyed(HttpSessionEvent event) {
		HttpSession session = event.getSession();
		ServletContext application = session.getServletContext();
		ConcurrentHashMap<String, HttpSession> userHash = null;
		Object obj = application.getAttribute(SessionKey.APPLICATION_ONLINE_USER);
		if (obj != null) {// 对象不为空时切在线人数大于0则减去一位在线用户
			userHash = (ConcurrentHashMap<String, HttpSession>) obj;
			HttpSession removeSession = userHash.remove(session.getId());
			Object serverId = removeSession.getAttribute(SessionKey.SESSION_SERVERID);
			LOG.debug(
					String.valueOf(serverId) + "有用户退出访问，sessionID=" + session.getId() + "，平台在线用户数为：" + userHash.size());
		} else {
			LOG.error("出现未知用户消亡,session_id=" + session.getId());
		}
	}

	public void requestDestroyed(ServletRequestEvent arg0) {}

	public void requestInitialized(ServletRequestEvent event) {
		request = (HttpServletRequest)event.getServletRequest();
	}

}